package com.wuyangnju.lj.simulation.master.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wuyangnju.lj.simulation.common.CommonStrings;
import com.wuyangnju.lj.simulation.common.Plan;
import com.wuyangnju.lj.simulation.master.service.ComputionException;
import com.wuyangnju.lj.simulation.master.service.ComputionService;

@SuppressWarnings("serial")
public class SubmitDataItemServlet extends HttpServlet {
	private static final Log log = LogFactory
			.getLog(SubmitDataItemServlet.class);

	private ComputionService computionService;
	{
		computionService = ComputionService.get();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/plain");

		int planX1 = 0, planX2 = 0, planX3 = 0, planX4 = 0, planX5 = 0;
		double dataItem = 0;

		try {
			planX1 = Integer.parseInt(req.getParameter(CommonStrings.PLAN_X1));
			planX2 = Integer.parseInt(req.getParameter(CommonStrings.PLAN_X2));
			planX3 = Integer.parseInt(req.getParameter(CommonStrings.PLAN_X3));
			planX4 = Integer.parseInt(req.getParameter(CommonStrings.PLAN_X4));
			planX5 = Integer.parseInt(req.getParameter(CommonStrings.PLAN_X5));

			Plan plan = new Plan(planX1, planX2, planX3, planX4, planX5);

			dataItem = Double.parseDouble(req.getParameter("dataItem"));

			log.info(" plan: " + plan + " dataItem: " + dataItem);

			long dataItemId = computionService.submitDataItem(plan, dataItem);
			resp.getWriter().println(dataItemId);

			log.info(" plan: " + plan + " dataItem: " + dataItem
					+ " dataItemId: " + dataItemId);

		} catch (ComputionException e) {
			resp.getWriter().println(
					CommonStrings.COMPUTION_EXCEPTION + ": " + e.getMessage());
			log.warn(CommonStrings.COMPUTION_EXCEPTION, e);
		} catch (Exception e) {
			log.error(e.toString());
			resp.getWriter().println(e.toString());
		}
	}
}
